#include "MainComponent.h"

//==============================================================================
MainComponent::MainComponent() {
    setSize(600, 400);


    StartText = juce::CharPointer_UTF8("开始");
    EndText = juce::CharPointer_UTF8("认输");
    SettingText = juce::CharPointer_UTF8("设置");
    AboutText = juce::CharPointer_UTF8("关于");

    StartButton.setButtonText(StartText);
    addAndMakeVisible(StartButton);
    StartButton.addListener(this);


    SettingButton.setButtonText(SettingText);
    addAndMakeVisible(SettingButton);
    SettingButton.addListener(this);

    AboutButton.setButtonText(AboutText);
    addAndMakeVisible(AboutButton);
    AboutButton.addListener(this);
    // 获取工作目录
    juce::File cur = juce::File::getSpecialLocation(juce::File::currentApplicationFile);
    // // 获取父目录
    juce::File parent = cur.getParentDirectory();
    juce::File file = parent.getChildFile("res/pictures/board.jpg");
    juce::File whitefile = parent.getChildFile("res/pictures/white_chess.png");
    juce::File blackfile = parent.getChildFile("res/pictures/black_chess.png");

    board = juce::ImageFileFormat::loadFrom(file);
    white = juce::ImageFileFormat::loadFrom(whitefile);
    black = juce::ImageFileFormat::loadFrom(blackfile);


    difficultyItems = {
        juce::String(juce::CharPointer_UTF8("1")),
        juce::String(juce::CharPointer_UTF8("2")),
        juce::String(juce::CharPointer_UTF8("3")),
        juce::String(juce::CharPointer_UTF8("4")),
        juce::String(juce::CharPointer_UTF8("5")),
        juce::String(juce::CharPointer_UTF8("6")),
        juce::String(juce::CharPointer_UTF8("7")),
        juce::String(juce::CharPointer_UTF8("8")),
        juce::String(juce::CharPointer_UTF8("9")),
        juce::String(juce::CharPointer_UTF8("10"))
    };
    xian = {
        juce::String(juce::CharPointer_UTF8("是")),
        juce::String(juce::CharPointer_UTF8("否"))
    };


    resized();
}

MainComponent::~MainComponent() {
    delete game;
    StartButton.removeListener(this);
    SettingButton.removeListener(this);
}

//==============================================================================
void MainComponent::paint(juce::Graphics& g) {
    // 绘制图片
    float width = getWidth();
    float height = getHeight();
    int imageWidth = board.getWidth() * height / board.getHeight();
    g.drawImageWithin(board, 0, 0, imageWidth, height,
                      juce::RectanglePlacement::xLeft | juce::RectanglePlacement::yTop | juce::RectanglePlacement::fillDestination,
                      false);

    if (game) {
        for (int i = 0; i < 15; i++) {
            for (int j = 0; j < 15; j++) {
                int x = BoardOffset + j * BoardGrid;
                int y = BoardOffset + i * BoardGrid;
                int destW = BoardGrid;
                int destH = BoardGrid;

                x -= BoardGrid * 0.5;
                y -= BoardGrid * 0.5;

                int chess = game->board[j][i];
                if (chess == -1) {
                    g.drawImageWithin(white, x, y, destW, destH,
                                      juce::RectanglePlacement::xLeft | juce::RectanglePlacement::yTop | juce::RectanglePlacement::fillDestination,
                                      false);
                }
                else if (chess == 1) {
                    g.drawImageWithin(black, x, y, destW, destH,
                                      juce::RectanglePlacement::xLeft | juce::RectanglePlacement::yTop | juce::RectanglePlacement::fillDestination,
                                      false);
                }
            }
        }
    }
}

void MainComponent::resized() {
    // 获取长宽
    int width = getWidth();
    int height = getHeight();
    // 打印
    juce::Rectangle<int> rect = getLocalBounds();

    AboutButton.setBounds(width - 100 - 20, height - 50 - 20 - 70 - 70, 100, 50);
    SettingButton.setBounds(width - 100 - 20, height - 50 - 20 - 70, 100, 50);
    StartButton.setBounds(width - 100 - 20, height - 50 - 20, 100, 50);

    BoardGrid = height / 15.3;
    BoardOffset = height / 15.3 / 1.5;
}

void MainComponent::buttonClicked(juce::Button* button) {
    if (button == &StartButton) {
        if (StartButton.getButtonText() == StartText) {
            StartButton.setButtonText(EndText);
            StartGame();
        }
        else if (StartButton.getButtonText() == EndText) {
            StartButton.setButtonText(StartText);
        }
    }
    else if (button == &SettingButton) {
        ShowSetting();
    }else if (button == &AboutButton) {
        ShowAbout();
    }
}


void MainComponent::StartGame() {
    if (game == nullptr) {
        game = new Gomoku();
    }
    game->changeDifficulty(difficulty);
    game->restart();
    state = 1;
    repaint();
}

void MainComponent::SetBoard(const std::string& str) {
    repaint();
}

void MainComponent::mouseDown(const juce::MouseEvent& event) {
    // Component::mouMainComponent::seDown(event);

    if (state == 1) {
        juce::Point<int> pos = event.getPosition();
        // 获取屏幕分辨率缩放比
        pos = pos - juce::Point<int>(BoardOffset, BoardOffset) + juce::Point<int>(BoardGrid * 0.5, BoardGrid * 0.5);
        int x = pos.x / BoardGrid;
        int y = pos.y / BoardGrid;
        if (x >= 0 && x <= 14 && y >= 0 && y <= 14) {
            if (game->placePiece(x, y)) {
                int nextx, nexty;
                game->getBestPos(nextx, nexty);
                game->placePiece(nextx, nexty);
                repaint();
            }
        }
    }
}


void MainComponent::ShowSetting() {
    auto* alertWindow = new juce::AlertWindow(SettingText, "", juce::MessageBoxIconType::NoIcon);


    enum AlertWindowResult {
        noButtonPressed,
        CANCEL,
        OK
    };


    alertWindow->addTextBlock(juce::CharPointer_UTF8("难度"));
    alertWindow->addComboBox(juce::CharPointer_UTF8("难度"), difficultyItems);
    alertWindow->getComboBoxComponent(juce::CharPointer_UTF8("难度"))->setSelectedItemIndex(difficulty);
    alertWindow->addTextBlock(juce::CharPointer_UTF8("先手"));
    alertWindow->addComboBox(juce::CharPointer_UTF8("先手"), xian);
    alertWindow->getComboBoxComponent(juce::CharPointer_UTF8("先手"))->setSelectedItemIndex(type ? 0 : 1);
    alertWindow->addButton(juce::CharPointer_UTF8("取消"), AlertWindowResult::CANCEL);
    alertWindow->addButton(juce::CharPointer_UTF8("確定"), AlertWindowResult::OK);

    // 屏幕中心
    juce::RectanglePlacement placement{
        juce::RectanglePlacement::yMid
        | juce::RectanglePlacement::xMid
        | juce::RectanglePlacement::doNotResize
    };

    auto bounds = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea.reduced(20);
    alertWindow->setBounds(placement.appliedTo(alertWindow->getBounds(), bounds));
    alertWindow->enterModalState(false, juce::ModalCallbackFunction::create([ref = SafePointer{this},alertWindow](int result) {
        if (ref == nullptr)
            return;
        if (result == AlertWindowResult::OK) {
            juce::ComboBox* diff = alertWindow->getComboBoxComponent(juce::CharPointer_UTF8("难度"));
            ref->difficulty = diff->getSelectedId() + 1;

            juce::ComboBox* xian = alertWindow->getComboBoxComponent(juce::CharPointer_UTF8("先手"));
            ref->type = xian->getSelectedId();
        }
    }), true);
}

void MainComponent::ShowAbout() {

    juce::String about = juce::CharPointer_UTF8("名称:\n育华五子棋\n作者：\n王梓亦  \n一切解释权归王梓亦所有！");

    auto* alertWindow = new juce::AlertWindow(juce::CharPointer_UTF8("软件说明"), about, juce::MessageBoxIconType::InfoIcon);
    juce::RectanglePlacement placement{
        juce::RectanglePlacement::yMid
        | juce::RectanglePlacement::xMid
        | juce::RectanglePlacement::doNotResize
    };
    alertWindow->addButton(juce::CharPointer_UTF8("確定"),1);

    auto bounds = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea.reduced(20);
    alertWindow->setBounds(placement.appliedTo(alertWindow->getBounds(), bounds));
    alertWindow->enterModalState(false,nullptr, true);
}